package com.fenrirtec.aepp.common.api;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.AdvImageDto;
import com.fenrirtec.aepp.common.service.AdvImageService;
import com.fenrirtec.aepp.common.service.impl.AdvImageServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.ImageUtils;
import com.fenrirtec.core.utils.JsonUtils;

public class AdvImageSearchAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(AdvImageSearchAPI.class);

	public AdvImageSearchAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		AdvImageService advImageService = new AdvImageServiceImpl();
		List<AdvImageDto> advImageDtoList = null;
		JSONObject root = new JSONObject();
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			
			if (jsonObj != null && !jsonObj.isEmpty() && jsonObj.containsKey("use_flag")) {
				advImageDtoList = advImageService.find(jsonObj.getBoolean("use_flag"));
			} else {
				advImageDtoList = advImageService.find(null);
			}
			
			if (advImageDtoList != null && advImageDtoList.size() > 0) {
				JSONArray jsonArray = new JSONArray();
				for (AdvImageDto advImageDto : advImageDtoList) {
					JSONObject obj = JsonUtils.fromBean(advImageDto);
					String path = advImageDto.getPath();
					if ((new File(path)).exists()) {
					    obj.put("image", "data:image/jpg;base64," + ImageUtils.imageToBase64(advImageDto.getPath()));
	                    jsonArray.add(obj);
					}
				}
				root.put("images", jsonArray);
			}
			
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}
		
		return root;
	}
}
